<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="page.param.name" placeholder="活动名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="info" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <el-button :loading="loading" class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="deleteData">
        删除
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="序号" type="index" width="50" />
      <el-table-column align="center" label="活动名称" prop="name"/>
      <el-table-column align="center" label="活动图片">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="baseUrl+'/file/img/'+scope.row.imgId"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="活动介绍" width="200" prop="detail"/>
      <el-table-column align="center" label="创建时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="150" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="viewClick(scope.row)">查看</el-button>
          <el-button type="text" size="small" @click="editClick(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-show="page.total>0" :total="page.total" :current-page="page.page" :page-size="page.limit" @current-change="fetchData" />
    <el-dialog title="活动" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="formRules">
        <el-form-item label="活动名称" label-width="150px" prop="name">
          <el-input
            ref="name"
            v-model="form.name"
            :readonly="state==='view'||state==='audit'"
            placeholder="请输入活动名称"
            name="name"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item label="活动介绍" label-width="150px" prop="detail">
          <el-input
            ref="detail"
            v-model="form.detail"
            :readonly="state==='view'||state==='audit'"
            placeholder="请输入活动介绍"
            name="detail"
            type="textarea"
            maxlength="100"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item label="活动图片" label-width="150px">
          <el-upload
            v-if="state==='add'||state==='edit'"
            class="upload-demo"
            :headers="headers"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :limit="1"
            :on-exected="handleExceed"
            :file-list="fileList"
            :action="baseUrl+'/file/upload'"
            :on-success="uploadSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
          <el-image
            v-if="form.imgId!==''"
            style="width: 100px; height: 100px"
            :src="baseUrl+'/file/img/'+form.imgId"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" v-if="state!=='view'" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { page, add, edit, deleteByIds } from '@/api/active'
import { Message } from 'element-ui'
import { validNotNull } from '@/utils/validate'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters([
      'roles'
    ])
  },
  data() {
    const validateText = (rule, value, callback) => {
      if (!validNotNull(value)) {
        callback(new Error('必填'))
      } else {
        callback()
      }
    }
    return {
      list: null,
      listLoading: true,
      baseUrl: 'http://localhost:8080',
      loading: false,
      page: {
        page: 1,
        size: 10,
        total: 0,
        param: { name: '' }
      },
      multipleSelection: [],
      dialogFormVisible: false,
      state: 'add',
      form: {
        name: '',
        detail: '',
        imgId: '',
        type: '',
        fileId: ''
      },
      fileList: [],
      formRules: {
        name: [{ required: true, trigger: 'blur', validator: validateText }],
        detail: [{ required: true, trigger: 'blur', validator: validateText }],
        type: [{ required: true, trigger: 'blur', validator: validateText }]
      },
      headers: { Authorization: getToken() }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取列表数据
    fetchData(val) {
      if (val != null && val !== '') {
        this.page.page = val
      }
      this.listLoading = true
      page(this.page).then(response => {
        this.list = response.result.records
        this.page.total = response.result.total
        this.listLoading = false
      })
    },
    // 选中改变
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 列表筛选
    handleFilter() {
      this.fetchData()
    },
    // 提交方法
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.imgId === '' || this.form.imgId === null) {
            this.$message.warning(`请上传课程图片！`)
            return false
          }
          if (this.state === 'add') {
            // 新增
            add(this.form).then(res => {
              if (res.code === '200'){
                this.dialogFormVisible = false
                this.fetchData()
                Message.success(res.result)
              }
            }).catch((err) => {
              console.log(err)
            })
          } else {
            // 修改
            edit(this.form).then(res => {
              if (res.code === '200'){
                this.dialogFormVisible = false
                this.fetchData()
                this.form = {
                  name: '',
                  detail: '',
                  imgId: '',
                  type: '',
                  fileId: ''
                }
                Message.success(res.result)
              }
            }).catch((err) => {
              console.log(err)
            })
          }
        } else {
          return false
        }
      })
    },
    // 新增
    handleCreate() {
      this.fileList = []
      this.form = {
        name: '',
        detail: '',
        imgId: '',
        fileId: '',
        type: ''
      }
      this.dialogFormVisible = true
    },
    // 查看
    viewClick(data) {
      this.state = 'view'
      this.dialogFormVisible = true
      this.form = data
    },
    // 修改
    editClick(data) {
      this.dialogFormVisible = true
      this.state = 'edit'
      this.form = data
    },
    // 删除
    deleteData() {
      this.loading = true
      const ids = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(item => {
          ids.push(item.id)
        })
        deleteByIds(ids).then(res => {
          this.loading = false
          if (res.code ==='200'){
            this.fetchData()
            Message.success(res.result)
          }
        }).catch((err) => {
          this.loading = false
          console.log(err)
        })
      } else {
        this.loading = false
        Message.error('请要删除的数据！')
      }
    },
    // 上传数量判断 -- 图片
    handleExceed(files, fileList) {
      if (files.length + fileList.length > 1) {
        this.$message.warning(`当前限制选择 1 张图片，共选择了 ${files.length + fileList.length} 张图片`)
      }
    },
    // 图片删除操作
    handleRemove() {
      this.form.imgId = ''
    },
    // 上传前置判断
    beforeUpload(file) {
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (suffix === 'jpg' || suffix === 'png') {
        return true
      } else {
        this.$message.error('仅支持上传jpg/png文件！')
        return false
      }
    },
    // 上传成功 -- 图片
    uploadSuccess(response, file, fileList) {
      if (response.code === '200') {
        this.form.imgId = response.result[0].id
        this.$message.success('上传成功！')
      } else {
        this.$message.error('上传失败，请重新上传或联系管理员！')
      }
    }
  }
}
</script>
<style scoped>

</style>
